package com.etymgiko.lyricshere.web.admin.song;

import com.etymgiko.lyricshere.manager.SongManager;
import com.etymgiko.lyricshere.manager.ArtistManager;
import com.etymgiko.lyricshere.model.Song;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 *
 * @author Ivan Holub
 */
public class SongValidator implements Validator {

    private SongManager songManager;

    public void setSongManager(SongManager songManager) {
        this.songManager = songManager;
    }
    
    public boolean supports(Class clazz) {
        return true;
    }

    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title", "error.song.title.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "code", "error.song.code.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lyrics", "error.song.lyrics.required");

        SongCommand command = (SongCommand) target;

        Long artistId;
        if (command.getId() == null) {
            //new
            artistId = Long.valueOf(command.getArtistId());
        } else {
            //edit
            artistId = songManager.getSong(Long.valueOf(command.getId())).getArtistId();
        }

        Song song = songManager.findSongByTitle(artistId, command.getTitle());
        if (song != null) {
            Long id = command.getId() == null ? null : Long.valueOf(command.getId());
            if (song.getTitle().equals(command.getTitle()) && !song.getId().equals(id)) {
                errors.rejectValue("title", "error.song.title.duplicate");
            }
        }

        song = songManager.findSongByCode(artistId, command.getCode());
        if (song != null) {
            Long id = command.getId() == null ? null : Long.valueOf(command.getId());
            if (song.getCode().equals(command.getCode()) && !song.getId().equals(id)) {
                errors.rejectValue("code", "error.song.code.duplicate");
            }
        }
    }
}